package com.example.service.impl;


import com.example.dto.ChatRequest;
import com.example.dto.Message;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ChatService {
    @Value("${deepseek.api.key}")
    private String apiKey;

    @Autowired
    private OkHttpClient okHttpClient;

    public String getChatResponse(String userMessage) throws IOException {
        // 构建消息列表
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("system", "You are a helpful assistant"));
        messages.add(new Message("user", userMessage));

        // 创建请求体
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setMessages(messages);

        // 转换JSON
        String requestBody = new ObjectMapper().writeValueAsString(chatRequest);

        RequestBody body = RequestBody.create(
            requestBody,
            MediaType.parse("application/json")
        );

        // 构建请求
        Request request = new Request.Builder()
            .url("https://api.deepseek.com/chat/completions")
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", "Bearer " + apiKey)
            .build();

        // 执行请求
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code());
            }

            JsonNode rootNode = new ObjectMapper().readTree(response.body().string());
            return rootNode.path("choices")
                        .get(0)
                        .path("message")
                        .path("content")
                        .asText();
        }
    }
}